from django.shortcuts import render
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view, permission_classes
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, JsonResponse
from .serializers import ConditionOrderSerializer
from .models import ConditionOrder
from .services.condition_order_logic import ConditionOrderThread
from util.const import *
from django.db.models import Q
import simplejson


# Create your views here.


@csrf_exempt
@api_view(http_method_names=['post', 'get', 'put', 'delete'])
@permission_classes((permissions.AllowAny,))
def condition_order(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        cookies = data["cookies"]
        data["cookies"] = simplejson.dumps(cookies)
        data['order_status'] = ORDER_STATUS_CREATE
        serializer = ConditionOrderSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            # ToDo: 执行条件单后台执行线程
            cot = ConditionOrderThread(cookies, serializer.instance)
            cot.start()
            return JsonResponse(serializer.data, status=200)
        return JsonResponse(serializer.errors, status=400)
    elif request.method == 'GET':
        user_name = request.GET.get('user_name')
        orders = ConditionOrder.objects.filter(user_name=user_name).filter(
            Q(order_status=ORDER_STATUS_CREATE) | Q(order_status=ORDER_STATUS_RUNNING)).order_by("order_time")
        serializer_orders = ConditionOrderSerializer(orders, many=True)
        return JsonResponse(serializer_orders.data, safe=False)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        condition_order_id = data["condition_order_id"]
        order_inst = ConditionOrder.objects.get(pk=condition_order_id)
        order_inst.order_status = data['order_status']
        order_inst_serializer = ConditionOrderSerializer(order_inst)
        serializer = ConditionOrderSerializer(order_inst, data=order_inst_serializer.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)
